<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
      <div>
        <h2 class="text-2xl font-bold">产品管理</h2>
        <p class="text-gray-500 mt-1">管理网站所有产品信息，支持添加、编辑和删除操作</p>
      </div>
      
      <div class="flex flex-wrap gap-3">
        <button class="btn btn-secondary" @click="refreshProducts">
          <i class="fa fa-refresh"></i>
          <span>刷新</span>
        </button>
        <button class="btn btn-primary" @click="showAddProductDialog">
          <i class="fa fa-plus"></i>
          <span>新增产品</span>
        </button>
        <button class="btn btn-secondary" @click="batchOperation('export')" :disabled="selectedProductIds.length === 0">
          <i class="fa fa-download"></i>
          <span>导出</span>
        </button>
        <button class="btn btn-danger" @click="batchOperation('delete')" :disabled="selectedProductIds.length === 0">
          <i class="fa fa-trash"></i>
          <span>批量删除</span>
        </button>
      </div>
    </div>
    
    <!-- 产品筛选 -->
    <div class="card p-4">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">所属站点</label>
          <select class="form-input" v-model="filters.siteId" @change="loadProducts">
            <option value="">全部站点</option>
            <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">所属分类</label>
          <select class="form-input" v-model="filters.categoryId" @change="filterProducts">
            <option value="">全部分类</option>
            <option 
              v-for="category in filteredCategories" 
              :key="category.id" 
              :value="category.id"
            >
              {{ getCategoryIndent(category.level) }}{{ category.name }}
            </option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">产品状态</label>
          <select class="form-input" v-model="filters.status" @change="filterProducts">
            <option value="">全部状态</option>
            <option value="draft">草稿</option>
            <option value="online">已上线</option>
            <option value="offline">已下线</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">关键词搜索</label>
          <div class="relative">
            <input 
              type="text" 
              class="form-input pl-10" 
              placeholder="产品名称或编号"
              v-model="filters.keyword"
              @keyup.enter="filterProducts"
            >
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>
      
      <div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">价格范围</label>
          <div class="flex gap-2">
            <input type="number" class="form-input" v-model="filters.minPrice" placeholder="最低">
            <span class="flex items-center text-gray-500">至</span>
            <input type="number" class="form-input" v-model="filters.maxPrice" placeholder="最高">
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">上架时间范围</label>
          <div class="flex gap-2">
            <input type="date" class="form-input" v-model="filters.startDate">
            <span class="flex items-center text-gray-500">至</span>
            <input type="date" class="form-input" v-model="filters.endDate">
          </div>
        </div>
        <div class="flex items-end">
          <button class="btn btn-primary w-full" @click="filterProducts">
            <i class="fa fa-search"></i>
            <span>搜索</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 产品列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="w-full">
          <thead>
            <tr class="bg-gray-50">
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-12">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="selectAll"
                  @change="handleSelectAll"
                >
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">产品信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">价格</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">库存</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上架时间</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="product in paginatedProducts" :key="product.id" class="hover:bg-gray-50 transition-colors">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="selectedProductIds"
                  :value="product.id"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap max-w-md">
                <div class="flex items-start gap-3">
                  <img 
                    :src="product.mainImage" 
                    :alt="product.name"
                    class="w-16 h-12 object-cover rounded flex-shrink-0"
                  >
                  <div>
                    <div class="font-medium text-gray-900 hover:text-primary" @click="viewProduct(product.id)">
                      {{ product.name }}
                    </div>
                    <div class="text-sm text-gray-500 mt-1">
                      编号: {{ product.sku }}
                    </div>
                    <div class="flex items-center gap-2 mt-1">
                      <span v-if="product.isRecommend" class="badge bg-success/10 text-success text-xs">推荐</span>
                      <span v-if="product.isNew" class="badge bg-primary/10 text-primary text-xs">新品</span>
                      <span v-if="product.isHot" class="badge bg-warning/10 text-warning text-xs">热销</span>
                    </div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ findCategoryName(product.categoryId) }}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div>
                  <span class="text-sm font-medium text-danger">¥{{ product.price.toFixed(2) }}</span>
                  <template v-if="product.originalPrice > product.price">
                    <span class="text-sm text-gray-500 line-through ml-2">¥{{ product.originalPrice.toFixed(2) }}</span>
                  </template>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ product.stock }}</span>
                <span class="text-xs text-gray-500 ml-1">件</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-900">{{ formatDate(product.onlineTime) }}</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  class="badge"
                  :class="getStatusBadgeClass(product.status)"
                >
                  {{ getStatusName(product.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <div class="flex justify-end gap-2">
                  <button 
                    class="text-primary hover:text-primary/80"
                    @click="previewProduct(product.id)"
                  >
                    预览
                  </button>
                  <button 
                    class="text-gray-600 hover:text-gray-900"
                    @click="showEditProductDialog(product.id)"
                  >
                    编辑
                  </button>
                  <button 
                    class="text-gray-600 hover:text-gray-900"
                    @click="toggleProductStatus(product.id, product.status)"
                  >
                    {{ product.status === 'online' ? '下线' : '上线' }}
                  </button>
                  <button 
                    class="text-danger hover:text-danger/80"
                    @click="confirmDeleteProduct(product.id)"
                  >
                    删除
                  </button>
                </div>
              </td>
            </tr>
            
            <tr v-if="filteredProducts.length === 0">
              <td colspan="8" class="px-6 py-12 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-cube text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">未找到产品</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  没有找到符合当前筛选条件的产品，请尝试调整筛选条件或点击"新增产品"创建
                </p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="filteredProducts.length > 0" class="px-6 py-4 border-t border-gray-200 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div class="text-sm text-gray-500">
          显示 {{ Math.min((currentPage-1)*pageSize + 1, filteredProducts.length) }} - {{ Math.min(currentPage*pageSize, filteredProducts.length) }} 条，共 {{ filteredProducts.length }} 个产品
        </div>
        <div class="flex items-center gap-2">
          <div class="text-sm">
            每页显示
            <select 
              class="ml-1 border border-gray-300 rounded px-2 py-1 text-sm"
              v-model="pageSize"
              @change="handlePageSizeChange"
            >
              <option value="10">10</option>
              <option value="20">20</option>
              <option value="50">50</option>
              <option value="100">100</option>
            </select>
            条
          </div>
          
          <div class="flex items-center gap-1">
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === 1"
              @click="currentPage = currentPage - 1"
            >
              <i class="fa fa-chevron-left text-xs"></i>
            </button>
            
            <button 
              v-for="page in visiblePages" 
              :key="page"
              class="w-8 h-8 flex items-center justify-center rounded"
              :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
              @click="currentPage = page"
            >
              {{ page }}
            </button>
            
            <button 
              class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
              :disabled="currentPage === totalPages"
              @click="currentPage = currentPage + 1"
            >
              <i class="fa fa-chevron-right text-xs"></i>
            </button>
          </div>
          
          <div class="text-sm">
            跳至
            <input 
              type="number" 
              class="ml-1 border border-gray-300 rounded px-2 py-1 text-sm w-16 text-center"
              v-model="jumpPage"
              :min="1"
              :max="totalPages"
              @keyup.enter="handleJumpPage"
            >
            页
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 产品表单对话框 -->
  <ProductFormDialog 
    :visible="productDialogVisible"
    :is-edit-mode="isEditMode"
    :current-id="currentEditingId"
    :sites="sites"
    :categories="categories"
    :product-form="productForm"
    @close="closeProductDialog"
    @save="saveProduct"
    @open-media-library="openMediaLibrary"
  />
  
  <!-- 媒体库对话框 -->
  <MediaLibraryDialog 
    :visible="mediaLibraryVisible"
    :selected-images="selectedMediaImages"
    @close="closeMediaLibrary"
    @confirm="confirmMediaSelection"
  />
  
  <!-- 删除确认对话框 -->
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="deleteDialogVisible">
      <div class="bg-white rounded-xl w-full max-w-md">
        <div class="p-6 text-center">
          <div class="w-16 h-16 rounded-full bg-danger/10 flex items-center justify-center mx-auto mb-4">
            <i class="fa fa-exclamation-triangle text-2xl text-danger"></i>
          </div>
          <h3 class="text-xl font-bold mb-2">确认删除</h3>
          <p class="text-gray-500">
            您确定要删除这{{ deleteBatch ? '些' : '个' }}产品吗？删除后将无法恢复。
          </p>
        </div>
        
        <div class="p-4 border-t border-gray-100 flex justify-center gap-3">
          <button class="btn btn-secondary" @click="deleteDialogVisible = false">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-danger" @click="deleteConfirmed">
            <i class="fa fa-trash"></i>
            <span>确认删除</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import ProductFormDialog from './components/ProductFormDialog.vue'
import MediaLibraryDialog from './components/MediaLibraryDialog.vue'

const router = useRouter()

// 站点数据
const sites = ref([
  { id: 1, name: '时尚服装商城' },
  { id: 2, name: '电子产品商店' },
  { id: 3, name: '家居用品店' }
])

// 产品分类数据
const categories = ref([
  { id: 1, name: '男装', parentId: 0, siteId: 1, level: 0 },
  { id: 2, name: '女装', parentId: 0, siteId: 1, level: 0 },
  { id: 3, name: '上衣', parentId: 1, siteId: 1, level: 1 },
  { id: 4, name: '裤子', parentId: 1, siteId: 1, level: 1 },
  { id: 5, name: '手机', parentId: 0, siteId: 2, level: 0 },
  { id: 6, name: '电脑', parentId: 0, siteId: 2, level: 0 },
  { id: 7, name: '智能手机', parentId: 5, siteId: 2, level: 1 },
  { id: 8, name: '笔记本电脑', parentId: 6, siteId: 2, level: 1 },
  { id: 9, name: '客厅家具', parentId: 0, siteId: 3, level: 0 },
  { id: 10, name: '卧室家具', parentId: 0, siteId: 3, level: 0 }
])

// 产品数据
const products = ref([
  {
    id: 1,
    name: '纯棉修身男士T恤',
    sku: 'CL-M-T001',
    categoryId: 3,
    siteId: 1,
    mainImage: 'https://picsum.photos/id/1005/300/300',
    images: [
      'https://picsum.photos/id/1005/800/800',
      'https://picsum.photos/id/1012/800/800',
      'https://picsum.photos/id/1025/800/800'
    ],
    price: 99.00,
    originalPrice: 129.00,
    stock: 156,
    salesCount: 235,
    status: 'online',
    isNew: false,
    isHot: true,
    isRecommend: true,
    attributes: [
      { name: '颜色', value: '白色,黑色,蓝色' },
      { name: '尺寸', value: 'S,M,L,XL' },
      { name: '材质', value: '100%棉' }
    ],
    description: '采用优质纯棉面料，舒适透气，修身版型，适合各种场合穿着。',
    detailContent: '<p>产品详细描述内容...</p>',
    createTime: '2023-04-15',
    updateTime: '2023-06-10',
    onlineTime: '2023-04-16'
  },
  {
    id: 2,
    name: '商务休闲男士牛仔裤',
    sku: 'CL-M-P002',
    categoryId: 4,
    siteId: 1,
    mainImage: 'https://picsum.photos/id/1011/300/300',
    images: [
      'https://picsum.photos/id/1011/800/800',
      'https://picsum.photos/id/1013/800/800'
    ],
    price: 199.00,
    originalPrice: 259.00,
    stock: 89,
    salesCount: 156,
    status: 'online',
    isNew: false,
    isHot: false,
    isRecommend: true,
    attributes: [
      { name: '颜色', value: '蓝色,黑色' },
      { name: '尺寸', value: '28,29,30,31,32' },
      { name: '面料', value: '棉弹牛仔布' }
    ],
    description: '经典直筒版型牛仔裤，舒适弹力面料，适合商务休闲场合。',
    detailContent: '<p>产品详细描述内容...</p>',
    createTime: '2023-03-20',
    updateTime: '2023-06-05',
    onlineTime: '2023-03-22'
  },
  {
    id: 3,
    name: '超薄笔记本电脑',
    sku: 'EP-C-001',
    categoryId: 8,
    siteId: 2,
    mainImage: 'https://picsum.photos/id/1/300/300',
    images: [
      'https://picsum.photos/id/1/800/800',
      'https://picsum.photos/id/2/800/800',
      'https://picsum.photos/id/3/800/800'
    ],
    price: 5999.00,
    originalPrice: 6499.00,
    stock: 45,
    salesCount: 78,
    status: 'online',
    isNew: true,
    isHot: true,
    isRecommend: true,
    attributes: [
      { name: '处理器', value: 'Intel i7' },
      { name: '内存', value: '16GB' },
      { name: '硬盘', value: '512GB SSD' },
      { name: '屏幕', value: '14英寸 2.5K' }
    ],
    description: '轻薄便携笔记本电脑，长续航，高性能，适合办公和娱乐。',
    detailContent: '<p>产品详细描述内容...</p>',
    createTime: '2023-05-10',
    updateTime: '2023-06-15',
    onlineTime: '2023-05-15'
  },
  {
    id: 4,
    name: '智能大屏手机',
    sku: 'EP-P-002',
    categoryId: 7,
    siteId: 2,
    mainImage: 'https://picsum.photos/id/160/300/300',
    images: [
      'https://picsum.photos/id/160/800/800',
      'https://picsum.photos/id/163/800/800'
    ],
    price: 3499.00,
    originalPrice: 3499.00,
    stock: 120,
    salesCount: 95,
    status: 'online',
    isNew: true,
    isHot: false,
    isRecommend: false,
    attributes: [
      { name: '处理器', value: '骁龙8 Gen2' },
      { name: '内存', value: '8GB+256GB' },
      { name: '屏幕', value: '6.7英寸 OLED' },
      { name: '电池', value: '5000mAh' },
      { name: '摄像头', value: '5000万像素主摄' }
    ],
    description: '高性能智能手机，高清大屏，大电池长续航，拍照效果出色。',
    detailContent: '<p>产品详细描述内容...</p>',
    createTime: '2023-06-01',
    updateTime: '2023-06-01',
    onlineTime: '2023-06-05'
  },
  {
    id: 5,
    name: '现代简约沙发',
    sku: 'HM-L-001',
    categoryId: 9,
    siteId: 3,
    mainImage: 'https://picsum.photos/id/1060/300/300',
    images: [
      'https://picsum.photos/id/1060/800/800',
      'https://picsum.photos/id/1062/800/800',
      'https://picsum.photos/id/1066/800/800'
    ],
    price: 2999.00,
    originalPrice: 3599.00,
    stock: 15,
    salesCount: 23,
    status: 'offline',
    isNew: false,
    isHot: false,
    isRecommend: false,
    attributes: [
      { name: '材质', value: '科技布' },
      { name: '颜色', value: '灰色,米白色' },
      { name: '尺寸', value: '三人位 220cm' },
      { name: '风格', value: '现代简约' }
    ],
    description: '现代简约风格沙发，舒适透气科技布面料，易清洁，适合多种装修风格。',
    detailContent: '<p>产品详细描述内容...</p>',
    createTime: '2023-02-15',
    updateTime: '2023-05-20',
    onlineTime: '2023-02-20'
  }
])

// 筛选条件
const filters = reactive({
  siteId: '',
  categoryId: '',
  status: '',
  keyword: '',
  minPrice: '',
  maxPrice: '',
  startDate: '',
  endDate: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const jumpPage = ref(1)
const selectAll = ref(false)
const selectedProductIds = ref([])

// 对话框状态
const productDialogVisible = ref(false)
const isEditMode = ref(false)
const currentEditingId = ref(null)
const mediaLibraryVisible = ref(false)
const selectedMediaImages = ref([])
const deleteDialogVisible = ref(false)
const deleteBatch = ref(false)
const deleteProductIds = ref([])

// 产品表单数据
const productForm = reactive({
  name: '',
  sku: '',
  siteId: '',
  categoryId: '',
  mainImage: '',
  images: [],
  price: 0,
  originalPrice: 0,
  stock: 0,
  status: 'draft',
  isNew: false,
  isHot: false,
  isRecommend: false,
  attributes: [],
  description: '',
  detailContent: ''
})

// 筛选后的产品列表
const filteredProducts = computed(() => {
  return products.value.filter(product => {
    // 站点筛选
    if (filters.siteId && product.siteId != filters.siteId) return false
    
    // 分类筛选
    if (filters.categoryId && product.categoryId != filters.categoryId) return false
    
    // 状态筛选
    if (filters.status && product.status != filters.status) return false
    
    // 关键词筛选
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      if (!product.name.toLowerCase().includes(keyword) && 
          !product.sku.toLowerCase().includes(keyword)) {
        return false
      }
    }
    
    // 价格范围筛选
    if (filters.minPrice && product.price < filters.minPrice) return false
    if (filters.maxPrice && product.price > filters.maxPrice) return false
    
    // 日期范围筛选
    if (filters.startDate && product.onlineTime < filters.startDate) return false
    if (filters.endDate && product.onlineTime > filters.endDate) return false
    
    return true
  })
})

// 分页后的产品列表
const paginatedProducts = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredProducts.value.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(filteredProducts.value.length / pageSize.value) || 1
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const endPage = Math.min(totalPages.value, startPage + maxVisible - 1)
  
  // 调整起始页，确保显示足够的页码
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 筛选后的分类列表（根据选中的站点）
const filteredCategories = computed(() => {
  if (!filters.siteId) return []
  return categories.value.filter(cat => cat.siteId == filters.siteId)
})

// 初始化
onMounted(() => {
  jumpPage.value = 1
})

// 加载产品（模拟API调用）
const loadProducts = () => {
  currentPage.value = 1
  selectedProductIds.value = []
  selectAll.value = false
}

// 筛选产品
const filterProducts = () => {
  currentPage.value = 1
  selectedProductIds.value = []
  selectAll.value = false
}

// 刷新产品
const refreshProducts = () => {
  selectedProductIds.value = []
  selectAll.value = false
}

// 全选/取消全选
const handleSelectAll = () => {
  if (selectAll.value) {
    selectedProductIds.value = paginatedProducts.value.map(product => product.id)
  } else {
    selectedProductIds.value = []
  }
}

// 处理分页大小变化
const handlePageSizeChange = () => {
  currentPage.value = 1
  jumpPage.value = 1
}

// 处理页码跳转
const handleJumpPage = () => {
  let page = parseInt(jumpPage.value)
  if (isNaN(page) || page < 1) {
    page = 1
  } else if (page > totalPages.value) {
    page = totalPages.value
  }
  currentPage.value = page
}

// 批量操作
const batchOperation = (operation) => {
  if (selectedProductIds.value.length === 0) return
  
  if (operation === 'delete') {
    deleteBatch.value = true
    deleteProductIds.value = [...selectedProductIds.value]
    deleteDialogVisible.value = true
  } else if (operation === 'export') {
    // 模拟导出操作
    alert(`已导出 ${selectedProductIds.value.length} 个产品`)
  }
}

// 显示新增产品对话框
const showAddProductDialog = () => {
  isEditMode.value = false
  currentEditingId.value = null
  productDialogVisible.value = true
  
  // 生成随机SKU
  const randomStr = Math.random().toString(36).substring(2, 8)
  const sku = `PRO-${randomStr}`
  
  // 重置表单
  Object.assign(productForm, {
    name: '',
    sku: sku,
    siteId: filters.siteId || '',
    categoryId: '',
    mainImage: '',
    images: [],
    price: 0,
    originalPrice: 0,
    stock: 0,
    status: 'draft',
    isNew: false,
    isHot: false,
    isRecommend: false,
    attributes: [{ name: '', value: '' }],
    description: '',
    detailContent: ''
  })
}

// 显示编辑产品对话框
const showEditProductDialog = (id) => {
  const product = products.value.find(p => p.id === id)
  if (!product) return
  
  isEditMode.value = true
  currentEditingId.value = id
  productDialogVisible.value = true
  
  // 填充表单
  Object.assign(productForm, {
    name: product.name,
    sku: product.sku,
    siteId: product.siteId,
    categoryId: product.categoryId,
    mainImage: product.mainImage,
    images: [...product.images],
    price: product.price,
    originalPrice: product.originalPrice,
    stock: product.stock,
    status: product.status,
    isNew: product.isNew,
    isHot: product.isHot,
    isRecommend: product.isRecommend,
    attributes: [...product.attributes],
    description: product.description,
    detailContent: product.detailContent
  })
}

// 关闭产品对话框
const closeProductDialog = () => {
  productDialogVisible.value = false
}

// 保存产品
const saveProduct = () => {
  if (isEditMode.value) {
    // 编辑现有产品
    const index = products.value.findIndex(p => p.id === currentEditingId.value)
    if (index !== -1) {
      const updated = {
        ...products.value[index],
        ...productForm,
        updateTime: new Date().toLocaleDateString(),
        // 如果状态变为已上线且之前未上线过，则设置上线时间
        onlineTime: productForm.status === 'online' && products.value[index].status !== 'online' 
          ? new Date().toLocaleDateString() 
          : products.value[index].onlineTime
      }
      products.value[index] = updated
    }
  } else {
    // 新增产品
    const newId = Math.max(...products.value.map(p => p.id), 0) + 1
    const now = new Date().toLocaleDateString()
    products.push({
      id: newId,
      ...productForm,
      salesCount: 0,
      createTime: now,
      updateTime: now,
      onlineTime: productForm.status === 'online' ? now : ''
    })
  }
  
  // 关闭对话框
  productDialogVisible.value = false
  alert(isEditMode.value ? '产品更新成功' : '产品创建成功')
}

// 打开媒体库
const openMediaLibrary = (type = 'multi') => {
  // 记录当前选中的图片，用于媒体库回显
  selectedMediaImages.value = [...productForm.images]
  mediaLibraryVisible.value = true
}

// 关闭媒体库
const closeMediaLibrary = () => {
  mediaLibraryVisible.value = false
}

// 确认媒体选择
const confirmMediaSelection = (images) => {
  productForm.images = [...images]
  // 如果没有主图，自动设置第一张为主要图片
  if (!productForm.mainImage && images.length > 0) {
    productForm.mainImage = images[0]
  }
  mediaLibraryVisible.value = false
}

// 确认删除产品
const confirmDeleteProduct = (id) => {
  deleteBatch.value = false
  deleteProductIds.value = [id]
  deleteDialogVisible.value = true
}

// 确认删除
const deleteConfirmed = () => {
  // 执行删除
  products.value = products.value.filter(product => !deleteProductIds.value.includes(product.id))
  
  // 更新选中状态
  selectedProductIds.value = selectedProductIds.value.filter(id => !deleteProductIds.value.includes(id))
  if (selectedProductIds.value.length === 0) {
    selectAll.value = false
  }
  
  // 关闭对话框
  deleteDialogVisible.value = false
  alert(`已删除 ${deleteProductIds.value.length} 个产品`)
}

// 查看产品详情
const viewProduct = (id) => {
  router.push(`/product-detail?id=${id}`)
}

// 预览产品
const previewProduct = (id) => {
  alert(`预览产品 ID: ${id}`)
}

// 切换产品状态
const toggleProductStatus = (id, currentStatus) => {
  const index = products.value.findIndex(p => p.id === id)
  if (index !== -1) {
    const newStatus = currentStatus === 'online' ? 'offline' : 'online'
    products.value[index].status = newStatus
    products.value[index].updateTime = new Date().toLocaleDateString()
    
    // 如果状态变为已上线且之前未上线过，则设置上线时间
    if (newStatus === 'online' && !products.value[index].onlineTime) {
      products.value[index].onlineTime = new Date().toLocaleDateString()
    }
    
    alert(`产品已${newStatus === 'online' ? '上线' : '下线'}`)
  }
}

// 辅助函数：查找分类名称
const findCategoryName = (id) => {
  const category = categories.value.find(cat => cat.id === id)
  return category ? category.name : '未知分类'
}

// 辅助函数：获取分类缩进
const getCategoryIndent = (level) => {
  return '　'.repeat(level) // 使用全角空格实现缩进
}

// 辅助函数：获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    'draft': '草稿',
    'online': '已上线',
    'offline': '已下线'
  }
  return statusMap[status] || '未知状态'
}

// 辅助函数：获取状态标签样式
const getStatusBadgeClass = (status) => {
  const classMap = {
    'draft': 'bg-gray-100 text-gray-600',
    'online': 'bg-success/10 text-success',
    'offline': 'bg-danger/10 text-danger'
  }
  return classMap[status] || 'bg-gray-100 text-gray-600'
}

// 辅助函数：格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return dateString
}
</script>